class Group < Entity
	has_many :administrates, :dependent => :destroy
	has_many :admins, :through => :administrates, :source => :entity
	
  before_save :ensure_introverted_set
	#before_destroy :destroy_group_cleanup
	
	#validates :admins, :presence => true	
	
	#---------------------------------------- these methods for private use to automate group setup
	def ensure_admin_is_created(founder_id) # Michael
		Administrate.create(:group_id => self.id, :entity_id => founder_id)		
	end
	
	def ensure_friendship_is_created(founder_id) # Michael
		friend = Friendship.create(:entity_id => founder_id, :friend_id => self.id, :accepted => true)
  end
  
  def ensure_introverted_set
    return !self.introverted.nil?  
  end
	
	def initialise_relationships(founder_id) # Michael
		ensure_friendship_is_created(founder_id)
		ensure_admin_is_created(founder_id)
	end
	
	#---------------------------------------- these methods for public use to edit admins
	def grant_admin(new_id) # Michael
		Administrate.create(:group_id => self.id, :entity_id => new_id)
	end
	
	def revoke_admin(admin_id) # Michael
		unless self.admins.count < 2
			Administrate.destroy(Administrate.find_by_entity_id(admin_id))
		end
	end
	
	#---------------------------------------- these methods for group messages
	def message_all_members(subject, message) # Michael
		members = self.find_friends
		members.each do |m|
			create_private_message(m.id, subject, message)
		end
	end
	
end
